<template>
    <!-- <el-button type="primary" style="margin-left: 16px" @click="drawer = true">
        open
    </el-button> -->
    <!--头像的模式上传图片-->
    <el-avatar shape="square" :size="100" :src="props.modelValue" @click="drawer = true">
        <img src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"/>
    </el-avatar>

    <el-drawer v-model="drawer" title="I am the title" direction="ttb" size="40%">

        <el-upload v-model:file-list="fileList" list-type="picture-card" :auto-upload="false" :on-change="onChange">
            <el-icon>
                <Plus />
            </el-icon>

            <template #file="{ file }">
                <div>
                    <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                    <span class="el-upload-list__item-actions">
                        <span class="el-upload-list__item-preview" @click="getImgUrl(file.url)">
                            <el-icon><zoom-in /></el-icon>
                        </span>
                    </span>
                </div>
            </template>
        </el-upload>
    </el-drawer>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { UploadApi } from '@/api'
import { onMounted } from 'vue'
import { ElMessage } from 'element-plus'

const drawer = ref(false)
const imgurl = ref('')
const fileList = ref([
  {
    name: 'food.jpeg',
    url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
    },
])


//定义函数 处理图片信息 提取base64信息
const onChange = (uploadFile: any, uploadFiles: any) => { 
    console.log(uploadFile);
    console.log(uploadFiles);
    let name = uploadFile.name;
    let file = uploadFile.raw
    let reader = new FileReader()
    reader.readAsDataURL(file)
    //读取图片事件
    reader.onload = () => {
        //base64格式的图片信息
        console.log(reader.result)
        uploadImage(name,reader.result)
    }

}
onMounted(()=>{
    CellUploadApi()
})
//图片上传
const uploadImage = (name:string , base64:any) => { 
    UploadApi.upload.cell({ name: name, base64: base64 }).then((res: any) => {
        ElMessage.success(res.msg)
    })
}

//父子通信 props 父向子   emit 子通知父
const props = defineProps({
    modelValue: {
        type: String,
        default: ''
    }
})

const emit = defineEmits(['update:modelValue'])


//获取图片列表信息
const CellUploadApi = () =>{
    UploadApi.imglist.cell().then((res: any) => {
        console.log(res)
        fileList.value = res
    })
}

//获取图片的url地址
const getImgUrl = (imageurl: string)=>{
    // console.log(imageurl);
    // imgurl.value = imageurl
    emit('update:modelValue',imageurl)

    drawer.value = false
}


</script>

<style scoped>

</style>